import React, { useEffect, useState } from 'react'
import './index.less'
import { Button, CellGroup, Form, FormItem, Icon } from '@antmjs/vantui'
import { Input, View } from '@tarojs/components'
import { showToast } from '@tarojs/taro'
import { cacheSetAuthInfoSync } from '@/cache'
import { passwordLogin } from '@/services'
import { wrapToast } from '@/utils/request'

interface IProps {
  onRefresh: () => void
  setError: React.Dispatch<
    | React.SetStateAction<{
        code: string
        message: string
        data: any
      }>
    | undefined
  >
}

export default function Index(props: IProps) {
  const { onRefresh, setError } = props
  const form = Form.useForm()
  const [showPassword, setShowPassword] = useState(false)

  // 注册不能回调函数设置必填的提示文案
  useEffect(() => {
    form.registerRequiredMessageCallback((label) => {
      return `请输入${label}`
    })
  }, [])
  return (
    <View className={'indexContainer'}>
      <CellGroup>
        <Form
          initialValues={{
            userName: '',
            password: '',
          }}
          form={form}
          onFinish={async (errs, _params) => {
            const res = await wrapToast(
              () =>
                passwordLogin({
                  loginName: _params['loginName'],
                  password: _params['password'],
                }),
              '登录中...',
              (fieldName) => form.dispatch({ type: 'getFieldModel' }, fieldName)?.label || fieldName,
            )

            if (res) {
              cacheSetAuthInfoSync(res)
              setError(undefined)
              onRefresh()
            }
          }}
        >
          <FormItem
            labelClassName={'login-form-item1'}
            label={<Icon name="manager" />}
            labelName={'登录账号'}
            name="loginName"
            required
            feedback={'hidden'}
            requiredIcon={<></>}
            trigger="onInput"
            validateTrigger="onBlur"
            // taro的input的onInput事件返回对应表单的最终值为e.detail.value
            valueFormat={(e) => e.detail.value}
          >
            <Input placeholder="请输入登录账号" />
          </FormItem>
          <FormItem
            labelClassName={'login-form-item1'}
            label={<Icon name="lock" />}
            labelName={'登录密码'}
            name="password"
            required
            feedback={'hidden'}
            requiredIcon={<></>}
            trigger="onInput"
            validateTrigger="onBlur"
            // taro的input的onInput事件返回对应表单的最终值为e.detail.value
            valueFormat={(e) => e.detail.value}
            renderRight={<Icon name="eye-o" onClick={() => setShowPassword(!showPassword)} />}
          >
            <Input password={!showPassword} placeholder="请输入登录密码" />
          </FormItem>
        </Form>
      </CellGroup>
      <Button
        className={'password-login-btn'}
        type="primary"
        onClick={() => {
          form.validateFields((errorMessage, fieldValues) => {
            if (errorMessage && errorMessage.length > 0) {
              showToast({
                title: errorMessage[0]!,
                icon: 'none',
                duration: 2000,
              })
            } else {
              form.submit()
            }
          })
        }}
      >
        登录
      </Button>
    </View>
  )
}
